package com.orangelife.utils;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.orangelife.exception.AppBizException;

public class StringUtils extends org.apache.commons.lang.StringUtils {
	
	public static void main(String[] args) throws AppBizException {
		String l = "4.232138";
		String l1 = "2000000.0000000000000000000";
//		System.out.println(isDoubleT(l));
//		System.out.println(isDoubleT(l1));
		System.out.println(trimZero(l));
		System.out.println(trimZero(l1));
		System.out.println(1.39 +1);
	}
	
	/**
	 * 判断是否有空格，有为true
	 * @author zhr
	 * @date 2015年7月31日
	 * @param str
	 * @return
	 */
	public static boolean haveSpace(String str) {

		boolean mat = str.matches("^(\\s|.*\\s+.*)$");
		return mat;
	}
	
	/**
	 * 用code来获取codeName（错误代号获取错误提示）
	 * 
	 * @param email
	 * @return
	 * @throws AppBizException 
	 */
	public static String getCode(Integer code) throws AppBizException {
		String codeName = ProConfig.getCode("code"+code);
		if(codeName==null){
			throw new AppBizException(101001, getCode(101001));
		}
		return codeName;
		
	}
	
	public static boolean isBlank(Object str)  {
	if(str==null){
		
		return true;
	}
	return isBlank(str.toString());
		
	}
	/**
	 * json对象转map(参数是String字符串)
	 * @param s
	 * @return
	 * @throws AppBizException
	 */
	public static Map<String, String> toMap(String s) throws AppBizException {
		JSONObject json=JSONObject.fromObject(s);
		Map<String, String> result = new HashMap<String, String>(); 
	    Iterator<String> iterator = json.keys(); 
	    String key = null; 
	    String value = null; 
	    while (iterator.hasNext()) 
	    { 
	        key = iterator.next(); 
	        value = json.getString(key); 
	        if(value==null||value.equals("null")){
	        	value = null;
	        }
	        result.put(key, value); 
	    }
		return result; 
	}
	
	/**
	 * json list转map(参数是String字符串)
	 * @param s
	 * @return
	 * @throws AppBizException
	 */
	public static List<Map<String, String>> jsonListToMap(String s) throws AppBizException {
		JSONArray jsonArray = JSONArray.fromObject(s);
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		
		for (int k = 0; k < jsonArray.size(); k++) {
			Map<String, String> result = new HashMap<String, String>();
			String strObject = jsonArray.get(k).toString();
			JSONObject jsonObject = JSONObject
					.fromObject(strObject);
			 Iterator<String> iterator = jsonObject.keys(); 
			    String key = null; 
			    String value = null; 
			    while (iterator.hasNext()) 
			    { 
			        key = iterator.next(); 
			        value = jsonObject.getString(key); 
			        if(value==null||value.equals("null")){
			        	value = null;
			        }
			        result.put(key, value); 
			    }
			    list.add(result);
		}
		
		return list; 
	}
	
	
	
	/**
	 * 判断输入的字符串参数是否为空
	 * 
	 * @return boolean 空则返回true,非空则flase
	 */
	public static boolean isEmpty(String input) {
		return null == input || 0 == input.length()
				|| 0 == input.replaceAll("\\s", "").length();
	}

	/**
	 * 手机字段正则表达式
	 */
	private static final String MOBILE_PATTERN = "^13[0-9]{9}|15[012356789][0-9]{8}|18[0256789][0-9]{8}|147[0-9]{8}$";
	/**
	 * 
	 */
	private static final String INT_PATTERN = "^[0-9_]+$";
	/**
	 * 
	 */
	private static final String INT_PATTERN2 = "^[-+]?[0-9_]+$";
	
	

	/**
	 * 判断字符串是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isInt(String str) {
		return str.matches(INT_PATTERN);
	}

	/**
	 * 隐藏手机字符串部分字段
	 * 
	 * @param mobileStr
	 * @return
	 */
	public static String mobileFilter(String mobileStr) {
		return mobileStr.substring(0, 3) + "****" + mobileStr.substring(7, 11);
	}

	/**
	 * 隐藏邮箱字符串部分字段
	 * 
	 * @param mailStr
	 * @return
	 */
	public static String mailFilter(String mailStr) {
		String[] email = mailStr.split("@");
		String tempStr = email[0].substring(0, 3);
		for (int i = 0; i < email[0].length() - 3; i++) {
			tempStr += "*";
		}
		tempStr += "@";
		tempStr += email[1];
		return tempStr;
	}

	/**
	 * 隐藏银行卡号字符串部分字段,只显示前6后4位
	 * 
	 * @param mobileStr
	 * @return
	 */
	public static String cardNoFilter(String cardNoStr) {
		return cardNoStr.substring(0, 6) + "******"
				+ cardNoStr.substring(cardNoStr.length() - 4);
	}

	/**
	 * 检验手机号的准确性
	 * 
	 * @param mobileNum
	 * @return
	 */
	public static boolean isMobile(String mobileNum) {
		return mobileNum.matches(MOBILE_PATTERN);
	}

	/**
	 * 字节级切割,确保切割出的字符对应的字节数小等于传入参数。
	 * <p>
	 * 且字符完整
	 * 
	 * @param input
	 *            输入字符串
	 * @param charset
	 *            字符集
	 * @param max
	 *            最大字节数
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String spiltByByteMaxLength(String input, String charset,
			int max) throws UnsupportedEncodingException {
		if (input == null)
			return null;
		int offset = 0;
		StringBuilder sb = new StringBuilder(max);
		for (int i = 0; i < input.length(); i++) {
			offset += input.substring(i, i + 1).getBytes(charset).length;
			if (offset > max)
				break;

			sb.append(input.charAt(i));
		}
		return sb.toString();
	}

	/**
	 * 获得传入商户编码下级所有商户的统计信息
	 * 
	 * @param merchantCode
	 * @return
	 */
	public static String merchantCodeStr(String merchantCode) {
		String merchantCodeStr = "substr(merchant_code,0,"
				+ merchantCode.length() + ") = '" + merchantCode
				+ "' and length(merchant_code) = " + merchantCode.length()
				+ "+4";
		return merchantCodeStr;
	}

	public static String merchantCodeStrForHql(String merchantCode) {
		String merchantCodeStr = "substring(merchantCode,0,"
				+ merchantCode.length() + ") = '" + merchantCode
				+ "' and length(merchantCode) = " + merchantCode.length()
				+ "+4";
		return merchantCodeStr;
	}

	/**
	 * 获得包括本级和下一级商户的统计信息
	 * 
	 * @param merchantCode
	 * @return
	 */
	public static String merchantCodeIncludeCurrentStr(String merchantCode) {
		String merchantCodeStr = "((substr(merchant_code,0,"
				+ merchantCode.length() + ") = '" + merchantCode
				+ "' and length(merchant_code) = " + merchantCode.length()
				+ "+4) or merchant_code = '" + merchantCode + "') ";
		return merchantCodeStr;
	}

	/**
	 * 获得创建下一级代理商的后四位码
	 * 
	 * @param merchantCode
	 * @return
	 */
	public static String getNextMerchantCode(String merchantCode) {
		String merchantCodeStr = "select max(nextCode)+1 from (select t.merchant_code,substr(t.merchant_code,"
				+ merchantCode.length()
				+ "+1) as nextCode from tb_merchant t where (substr(merchant_code,0,"
				+ merchantCode.length()
				+ ") = '"
				+ merchantCode
				+ "' and length(merchant_code) = "
				+ merchantCode.length()
				+ "+4) order by merchant_code)";
		return merchantCodeStr;
	}
public static String toString(Object obj){
	
	if(obj==null){
		
		return null;
	}else{
		
		return obj.toString();
	}
	
	
}



public static String toString(Object obj,String str2){
	
	if(obj==null||"".equals(obj.toString())){
		
		return str2;
	}else{
		
		return obj.toString();
	}
	
	
}
	public static String getFormerMonth(int i, String yearMonth) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		Date date = null;
		try {
			date = format.parse(yearMonth);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, -i); // 得到前i个月

		int month = cal.get(Calendar.MONTH) + 1;

		// Date kk=format.parse(df.format(new Date(date1)));
		return String.valueOf(month);
	}

	/**
	 * UUID长度判断 36位
	 * 
	 * @param content
	 * @return
	 * @throws AppBizException
	 */
	public static boolean getLength(String content, String errName)
			throws AppBizException {
		if (isBlank(content)) {
			throw new AppBizException(000002, "输入参数" + errName + "不可为空");
		}

		if (content.equals("0")) {
		} else {
			if (!content.matches("[A-Za-z0-9-]+")) {
				throw new AppBizException(000002, "内置错误：输入参数输入参数" + errName
						+ "格式错误");
			}

			if (content.length() < 36) {
				throw new AppBizException(000007, "内置错误：输入参数" + errName
						+ "长度不足");
			}

			if (content.length() > 36) {
				throw new AppBizException(000006, "内置错误：输入参数" + errName
						+ "长度超出");
			}
		}

		
		return true;
	}
	
	
	/**
	 * 数字 长度判断 17位
	 * 
	 * @param content
	 * @return
	 * @throws AppBizException
	 */
	public static boolean getNumLength(String content, String errName)
			throws AppBizException {
		if (isBlank(content)) {
			throw new AppBizException(000002, "输入参数" + errName + "不可为空");
		}

		if (content.equals("0")) {
		} else {
			if (!StringUtils.isInt(content)) {
				throw new AppBizException(000002, "内置错误：输入参数输入参数" + errName
						+ "格式错误");
			}

			if (content.length() < 17) {
				throw new AppBizException(000007, "内置错误：输入参数" + errName
						+ "长度不足");
			}

			if (content.length() > 17) {
				throw new AppBizException(000006, "内置错误：输入参数" + errName
						+ "长度超出");
			}
		}

		
		return true;
	}

	/**
	 * 类型判断 要为数字不限长度
	 * 
	 * @param content
	 * @return
	 * @throws AppBizException
	 */
	public static boolean getTypeLength(String content) throws AppBizException {

		if (!StringUtils.isInt(content)) {
			throw new AppBizException(000003, "内置错误：输入参数格式错误");
		}

		// if (content.length() > 1) {
		// throw new AppBizException(000006, "内置错误：输入参数长度超出");
		// }
		return true;
	}
	
	/**
	 * 类型判断 要为数字且一位
	 * 
	 * @param content
	 * @return
	 * @throws AppBizException
	 */
	public static boolean getTypeLengths(String content,String errName) throws AppBizException {

		if (!StringUtils.isInt(content)) {
			throw new AppBizException(000003, "内置错误：输入参数"+errName+"格式错误");
		}

		 if (content.length() > 1) {
		 throw new AppBizException(000006, "内置错误：输入参数"+errName+"长度超出");
		 }
		return true;
	}

	public static boolean isDouble(String str) {
        if(isBlank(str)){
	
	      return false;
           }
		if (str.contains(".")) {
			Pattern pattern = Pattern
					.compile("[-+]?[0-9]+(\\.[0-9]+)?");
			
		//	System.out.println(pattern.matcher(str).matches());

			return pattern.matcher(str).matches();
		} else {
			return str.matches(INT_PATTERN2);
		}

	}
	
	public static boolean isDoubleT(String str) {

			/*Pattern pattern = Pattern
					.compile("^(([1-9][0-9]{0,7})|0|0\\.[0-9]{1,2}|[1-9][0-9]{0,7}(\\.[0-9]{1,2})?)$");*/
		Pattern pattern = Pattern
				.compile("^([\\d]|[1-9][\\d]{0,7})(\\.[\\d]{1,2})?$");
			
			System.out.println(pattern.matcher(str).matches());

			return pattern.matcher(str).matches();

	}
	
	public static String getDistance(String str) throws AppBizException {
		String l =null;
		try {
			if(!isDouble(str)){
				throw new AppBizException(000003, "输入参数格式错误");
			}
			Double d = Double.valueOf(str)*100000;
			l = String.valueOf(Math.round(d));
		} catch (NumberFormatException ex) {
			throw new AppBizException(000003, "输入参数格式错误");
		}
		return l;
	}

	public static boolean isTime(String str) throws AppBizException {

		if (str.length() > 13 || str.length() < 13) {
			throw new AppBizException(002011, "时间戳格式错误");
		} else {
			if (!StringUtils.isInt(str)) {
				throw new AppBizException(002011, "时间戳格式错误");
			}
		}

		return true;
	}

	public static boolean isNull(String str) throws AppBizException {

		if (str.toLowerCase().equals("null")) {
			throw new AppBizException(000003, "输入参数格式错误");
		}

		return true;
	}
	
	public static boolean isNulls(String str,String errName) throws AppBizException {

		if (str.toLowerCase().equals("null")) {
			throw new AppBizException(000003, "输入参数"+errName+"格式错误,不能为null");
		}

		return true;
	}

	public static boolean isNullStr(String str) throws AppBizException {
		if (str != null) {
			if (StringUtils.isBlank(str)) {
				throw new AppBizException(000001, "未归类错误不能为''");
			}
		}

		return true;
	}
	/**取消数字.后多余的0*/
	public static String  trimZero(String source){
		

	if(source.indexOf(".")>0){
	
		source=source.replaceAll("0+?$", "");
		source=source.replaceAll("[.]$", "");
		
	}
	
	
	return source;
		
	}
	
	/**
	 * 判断第一个大写位置
	 * 
	 * @param suStr
	 * @return
	 */
	public static int getUpIndex(String suStr) {
		int index = 0;
		char str[] = suStr.toCharArray();
		for (int i = 0; i<str.length; i++) {

			if (Character.isUpperCase(str[i])) {
				index = i;
				break;
			}

		}
		return index;
	}
	
	public static String smaller(Object str1,Object str2) {
		if(str1==null){
			
			return StringUtils.toString(str2);
		}
          if(str2==null){
			
			return StringUtils.toString(str1);
		}
		if(str1.toString().compareTo(str2.toString())<0){
			
			return str1.toString();
		}
		return str2.toString();
	}
	public static String bigger(Object str1,Object str2) {
        if(str1==null){
			
			return StringUtils.toString(str2);
		}
          if(str2==null){
			
			return StringUtils.toString(str1);
		}
		if(str1.toString().compareTo(str2.toString())>0){
			
			return str1.toString();
		}
		return str2.toString();
	}
}
